/**
 * 机勘院智能业务系统 - 系统管理页面JavaScript
 */

// 全局变量
let systemResourceChart = null;
let darkMode = localStorage.getItem('darkMode') === 'true';
let resourceChart = null;

// 确保在页面加载完成后初始化
$(document).ready(function() {
    // 如果在系统管理页面，则初始化系统管理功能
    if (window.location.pathname.includes('/pages/system.html')) {
        initSystemPage();
    }
    
    // 否则，等待主页面调用相关函数
    // 这里不需要做任何事情，因为函数已经定义好，可以被主页面调用
});

/**
 * 初始化系统管理页面
 */
function initSystemPage() {
    console.log('初始化系统管理页面');
    
    // 初始化系统资源监控图表
    initSystemResourceChart();
    
    // 初始化暗色模式
    initDarkMode();
    
    // 初始化侧边栏
    initSidebar();
    
    // 初始化工具提示
    initTooltips();
    
    // 绑定事件处理
    bindEvents();
    
    // 启动实时数据更新
    startRealTimeUpdates();
    
    // 默认加载用户管理内容
    loadTabContent('users');
}

/**
 * 初始化工具提示
 */
function initTooltips() {
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
}

/**
 * 初始化侧边栏
 */
function initSidebar() {
    // 移动端侧边栏切换
    $('#sidebarToggle').on('click', function() {
        $('.deepseek-sidebar').toggleClass('show');
        $('#sidebarOverlay').toggleClass('show');
    });
    
    // 点击遮罩时关闭侧边栏
    $('#sidebarOverlay').on('click', function() {
        $('.deepseek-sidebar').removeClass('show');
        $(this).removeClass('show');
    });
    
    // 点击主内容区域时关闭侧边栏 (移动端)
    $('.deepseek-main').on('click', function() {
        if (window.innerWidth < 992 && $('.deepseek-sidebar').hasClass('show')) {
            $('.deepseek-sidebar').removeClass('show');
            $('#sidebarOverlay').removeClass('show');
        }
    });
}

/**
 * 初始化暗色模式
 */
function initDarkMode() {
    // 从localStorage获取主题模式
    darkMode = localStorage.getItem('darkMode') === 'true';
    
    if (darkMode) {
        $('body').addClass('dark-mode');
        $('#themeToggle i').removeClass('fa-moon').addClass('fa-sun');
    }
    
    $('#themeToggle').on('click', function() {
        darkMode = !darkMode;
        $('body').toggleClass('dark-mode');
        $(this).find('i').toggleClass('fa-moon fa-sun');
        localStorage.setItem('darkMode', darkMode);
        
        // 更新图表主题
        updateChartTheme();
    });
}

/**
 * 初始化系统资源监控图表
 */
function initSystemResourceChart() {
    const ctx = document.getElementById('systemResourceChart').getContext('2d');
    const chartConfig = {
        type: 'line',
        data: {
            labels: Array(30).fill('').map(function(_, i) { return (29-i) + '分钟前'; }),
            datasets: [{
                label: 'CPU使用率',
                data: generateRandomData(30, 20, 80),
                borderColor: '#2563eb',
                backgroundColor: 'rgba(37, 99, 235, 0.1)',
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    mode: 'index',
                    intersect: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100,
                    ticks: {
                        callback: function(value) {
                            return value + '%';
                        }
                    }
                }
            },
            interaction: {
                intersect: false,
                mode: 'index'
            }
        }
    };
    
    systemResourceChart = new Chart(ctx, chartConfig);
}

/**
 * 更新图表主题
 */
function updateChartTheme() {
    if (!resourceChart) return;
    
    // 更新图表主题颜色
    const isDark = $('body').hasClass('dark-mode');
    
    // 设置图表文字颜色
    resourceChart.options.scales.x.ticks.color = isDark ? '#ccd6dd' : '#555';
    resourceChart.options.scales.y.ticks.color = isDark ? '#ccd6dd' : '#555';
    resourceChart.options.scales.x.grid.color = isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)';
    resourceChart.options.scales.y.grid.color = isDark ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.1)';
    
    resourceChart.update();
}

/**
 * 生成随机数据
 * @param {number} count - 数据点数量
 * @param {number} min - 最小值
 * @param {number} max - 最大值
 * @returns {number[]} 随机数据数组
 */
function generateRandomData(count, min, max) {
    return Array(count).fill(0).map(function() { 
        return Math.floor(Math.random() * (max - min + 1)) + min;
    });
}

/**
 * 加载系统状态数据
 */
function loadSystemStats() {
    // 在实际应用中，这里应该通过API获取实时数据
    const stats = {
        systemAvailability: 98.2,
        activeUsers: 48,
        memoryUsage: 2.15,
        apiCallsPerMinute: 165
    };
    
    updateSystemStats(stats);
}

/**
 * 更新系统状态显示
 * @param {Object} stats - 系统状态数据
 */
function updateSystemStats(stats) {
    // 更新统计卡片
    $('.stat-card').each(function() {
        const $card = $(this);
        const $value = $card.find('.stat-value');
        const $change = $card.find('.stat-change');
        
        // 生成随机变化率
        const change = (Math.random() * 10 - 5).toFixed(1);
        const isPositive = change > 0;
        
        $change
            .toggleClass('positive', isPositive)
            .toggleClass('negative', !isPositive)
            .html('<i class="fas fa-arrow-' + (isPositive ? 'up' : 'down') + ' me-1"></i> ' + Math.abs(change) + '%');
    });
}

/**
 * 启动实时数据更新
 */
function startRealTimeUpdates() {
    // 每5秒更新一次系统资源监控图表
    setInterval(function() {
        if (systemResourceChart) {
            const newData = generateRandomData(1, 20, 80)[0];
            systemResourceChart.data.datasets[0].data.shift();
            systemResourceChart.data.datasets[0].data.push(newData);
            systemResourceChart.update('none');
        }
    }, 5000);
    
    // 每30秒更新一次系统状态
    setInterval(loadSystemStats, 30000);
}

/**
 * 绑定事件处理
 */
function bindEvents() {
    // 导航菜单点击事件
    $('.deepseek-nav-item').on('click', function(e) {
        const hasSubmenu = $(this).attr('data-bs-toggle') === 'collapse';
        const isExternalLink = $(this).attr('href') && $(this).attr('href').indexOf('../') === 0;
        
        // 如果是带子菜单的导航项或外部链接，则不阻止默认行为
        if (hasSubmenu || isExternalLink) return;
        
        e.preventDefault();
        
        // 更新活动状态
        $('.deepseek-nav-item').removeClass('active');
        $(this).addClass('active');
        
        // 根据data-tab属性加载对应内容
        const tabId = $(this).data('tab');
        if (tabId) {
            loadTabContent(tabId);
        }
    });
    
    // 系统资源监控切换按钮
    $('.btn-group .btn').on('click', function() {
        const $btn = $(this);
        const type = $btn.attr('data-type');
        
        // 更新按钮状态
        $btn.siblings().removeClass('active');
        $btn.addClass('active');
        
        // 更新图表数据
        updateResourceChart(type);
    });
    
    // 用户管理相关事件
    bindUserManagementEvents();
    
    // AI配置相关事件
    bindAiConfigEvents();
}

/**
 * 绑定用户管理相关事件
 */
function bindUserManagementEvents() {
    // 添加用户按钮事件
    $('#saveUserBtn').on('click', saveUser);
    
    // 用户表格中的按钮事件
    $(document).on('click', '.btn-outline-secondary[title="编辑用户"]', function() {
        const row = $(this).closest('tr');
        editUser(row);
    });
    
    $(document).on('click', '.btn-outline-secondary[title="查看详情"]', function() {
        const row = $(this).closest('tr');
        viewUserDetails(row);
    });
    
    $(document).on('click', '.btn-outline-danger, .btn-outline-success', function() {
        const row = $(this).closest('tr');
        toggleUserStatus(row);
    });
    
    // 搜索用户
    let searchTimeout;
    $('input[placeholder="搜索用户..."]').on('input', function() {
        clearTimeout(searchTimeout);
        const query = $(this).val().trim();
        
        searchTimeout = setTimeout(function() {
            searchUsers(query);
        }, 300);
    });
    
    // 角色和部门筛选
    $('.form-select').on('change', function() {
        filterUsers();
    });
}

/**
 * 更新系统资源监控图表
 * @param {string} type - 资源类型（cpu/memory/network）
 */
function updateResourceChart(type) {
    if (!systemResourceChart) return;
    
    const colors = {
        cpu: '#2563eb',
        memory: '#10b981',
        network: '#f59e0b'
    };
    
    const labels = {
        cpu: 'CPU使用率',
        memory: '内存使用率',
        network: '网络使用率'
    };
    
    systemResourceChart.data.datasets[0].label = labels[type];
    systemResourceChart.data.datasets[0].borderColor = colors[type];
    systemResourceChart.data.datasets[0].backgroundColor = colors[type] + '1a';
    systemResourceChart.data.datasets[0].data = generateRandomData(30, 20, 80);
    
    systemResourceChart.update();
}

/**
 * 搜索用户
 * @param {string} query - 搜索关键词
 */
function searchUsers(query) {
    // 在实际应用中，这里应该调用API进行搜索
    console.log('搜索用户:', query);
    
    // 模拟搜索结果
    const rows = $('.system-table tbody tr');
    rows.each(function() {
        const $row = $(this);
        const text = $row.text().toLowerCase();
        $row.toggle(text.includes(query.toLowerCase()));
    });
}

/**
 * 筛选用户
 */
function filterUsers() {
    const role = $('.form-select').eq(0).val();
    const department = $('.form-select').eq(1).val();
    
    // 在实际应用中，这里应该调用API进行筛选
    console.log('筛选用户:', { role: role, department: department });
    
    // 模拟筛选结果
    const rows = $('.system-table tbody tr');
    rows.each(function() {
        const $row = $(this);
        const rowRole = $row.find('td:eq(1)').text();
        const rowDepartment = $row.find('td:eq(2)').text();
        
        const roleMatch = role === 'all' || rowRole === role;
        const departmentMatch = department === 'all' || rowDepartment === department;
        
        $row.toggle(roleMatch && departmentMatch);
    });
}

/**
 * 查看用户详情
 * @param {jQuery} row - 用户表格行
 */
function viewUserDetails(row) {
    const username = row.find('.fw-bold').text();
    const email = row.find('.text-muted').text();
    const role = row.find('td:eq(1)').text();
    const department = row.find('td:eq(2)').text();
    const lastLogin = row.find('td:eq(3)').text();
    const status = row.find('.badge').text();
    
    const modalContent = [
        '<div class="modal fade" id="userDetailsModal" tabindex="-1">',
        '    <div class="modal-dialog">',
        '        <div class="modal-content">',
        '            <div class="modal-header">',
        '                <h5 class="modal-title">用户详情</h5>',
        '                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>',
        '            </div>',
        '            <div class="modal-body">',
        '                <div class="d-flex align-items-center mb-3">',
        '                    <div class="deepseek-avatar me-3">' + username[0].toUpperCase() + '</div>',
        '                    <div>',
        '                        <h6 class="mb-1">' + username + '</h6>',
        '                        <div class="text-muted">' + email + '</div>',
        '                    </div>',
        '                </div>',
        '                <table class="table">',
        '                    <tr>',
        '                        <th>角色</th>',
        '                        <td>' + role + '</td>',
        '                    </tr>',
        '                    <tr>',
        '                        <th>部门</th>',
        '                        <td>' + department + '</td>',
        '                    </tr>',
        '                    <tr>',
        '                        <th>状态</th>',
        '                        <td><span class="badge bg-' + (status === '活跃' ? 'success' : 'secondary') + '">' + status + '</span></td>',
        '                    </tr>',
        '                    <tr>',
        '                        <th>上次登录</th>',
        '                        <td>' + lastLogin + '</td>',
        '                    </tr>',
        '                </table>',
        '            </div>',
        '        </div>',
        '    </div>',
        '</div>'
    ].join('\n');
    
    // 移除现有的模态框
    $('#userDetailsModal').remove();
    
    // 添加新的模态框
    $('body').append(modalContent);
    
    // 显示模态框
    const modal = new bootstrap.Modal('#userDetailsModal');
    modal.show();
}

/**
 * 加载选项卡内容
 * @param {string} tabId - 选项卡ID
 */
function loadTabContent(tabId) {
    // 清空内容区域
    $('#system-content').empty();
    
    console.log('加载标签内容:', tabId);
    
    // 根据tabId加载对应内容
    switch(tabId) {
        case 'dashboard':
            loadResourceMonitoring();
            break;
        case 'users':
            loadUserManagement();
            break;
        case 'roles':
            loadPermissionSettings();
            break;
        case 'logs':
            loadSystemLogs();
            break;
        case 'backup':
            loadDataBackup();
            break;
        case 'ai-config':
            loadAiConfig();
            break;
        default:
            loadResourceMonitoring(); // 默认加载资源监控
    }
}

/**
 * 加载用户管理内容
 */
function loadUserManagement() {
    // 在实际应用中，这里应该通过API获取用户列表数据
    const users = [
        {
            username: 'admin',
            email: 'admin@example.com',
            role: '管理员',
            department: '系统管理部',
            lastLogin: '2025-03-02 12:30:45',
            status: '活跃'
        },
        {
            username: 'engineer01',
            email: 'engineer01@example.com',
            role: '工程师',
            department: '道路勘察部',
            lastLogin: '2025-03-01 09:15:22',
            status: '活跃'
        },
        {
            username: 'manager01',
            email: 'manager01@example.com',
            role: '项目经理',
            department: '项目管理部',
            lastLogin: '2025-02-28 16:45:10',
            status: '未登录'
        }
    ];
    
    // 构建用户管理内容
    const content = `
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">用户管理</h5>
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#userModal">
                    <i class="fas fa-plus me-1"></i>添加用户
                </button>
            </div>
            <div class="card-body">
                <div class="row g-3 mb-3">
                    <div class="col-md-4">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" class="form-control" placeholder="搜索用户...">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select">
                            <option value="all">所有角色</option>
                            <option value="admin">管理员</option>
                            <option value="manager">项目经理</option>
                            <option value="engineer">工程师</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select">
                            <option value="all">所有部门</option>
                            <option value="system">系统管理部</option>
                            <option value="project">项目管理部</option>
                            <option value="road">道路勘察部</option>
                        </select>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table system-table">
                        <thead>
                            <tr>
                                <th>用户信息</th>
                                <th>角色</th>
                                <th>部门</th>
                                <th>上次登录</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 用户列表将由JavaScript动态更新 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;
    
    $('#system-content').html(content);
    
    // 更新用户列表
    const tbody = $('.system-table tbody');
    tbody.empty();
    
    users.forEach(function(user) {
        const tr = $([
            '<tr>',
            '    <td>',
            '        <div class="d-flex align-items-center">',
            '            <div class="deepseek-avatar me-3">' + user.username[0].toUpperCase() + '</div>',
            '            <div>',
            '                <div class="fw-bold">' + user.username + '</div>',
            '                <div class="small text-muted">' + user.email + '</div>',
            '            </div>',
            '        </div>',
            '    </td>',
            '    <td>' + user.role + '</td>',
            '    <td>' + user.department + '</td>',
            '    <td>' + user.lastLogin + '</td>',
            '    <td><span class="badge bg-' + (user.status === '活跃' ? 'success' : 'secondary') + '">' + user.status + '</span></td>',
            '    <td>',
            '        <div class="btn-group btn-group-sm">',
            '            <button class="btn btn-outline-secondary" data-bs-toggle="tooltip" title="编辑用户">',
            '                <i class="fas fa-edit"></i>',
            '            </button>',
            '            <button class="btn btn-outline-secondary" data-bs-toggle="tooltip" title="查看详情">',
            '                <i class="fas fa-eye"></i>',
            '            </button>',
            '            <button class="btn btn-outline-' + (user.status === '活跃' ? 'danger' : 'success') + '" data-bs-toggle="tooltip" title="' + (user.status === '活跃' ? '禁用' : '启用') + '用户">',
            '                <i class="fas fa-' + (user.status === '活跃' ? 'ban' : 'check') + '"></i>',
            '            </button>',
            '        </div>',
            '    </td>',
            '</tr>'
        ].join('\n'));
        
        tbody.append(tr);
    });
    
    // 重新初始化工具提示
    initTooltips();
}

/**
 * 加载权限设置内容
 */
function loadPermissionSettings() {
    const content = `
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">权限设置</h5>
            </div>
            <div class="card-body">
                <div class="mb-4">
                    <h6>角色管理</h6>
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>角色名称</th>
                                    <th>描述</th>
                                    <th>权限</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>管理员</td>
                                    <td>系统管理员，拥有所有权限</td>
                                    <td>全部</td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-secondary">编辑</button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>项目经理</td>
                                    <td>项目管理人员</td>
                                    <td>项目管理、文件管理、知识库</td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-secondary">编辑</button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div>
                    <h6>权限项设置</h6>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-body">
                                    <h6>系统管理</h6>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="perm1">
                                        <label class="form-check-label" for="perm1">用户管理</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="perm2">
                                        <label class="form-check-label" for="perm2">权限设置</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    $('#system-content').html(content);
}

/**
 * 加载系统日志内容
 */
function loadSystemLogs() {
    const content = `
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">系统日志</h5>
                <div>
                    <button class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-download"></i> 导出日志
                    </button>
                    <button class="btn btn-sm btn-outline-danger">
                        <i class="fas fa-trash"></i> 清空日志
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table">
                        <thead>
                            <tr>
                                <th>时间</th>
                                <th>类型</th>
                                <th>用户</th>
                                <th>操作</th>
                                <th>详情</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>2025-03-02 14:30:15</td>
                                <td><span class="badge bg-info">登录</span></td>
                                <td>admin</td>
                                <td>用户登录</td>
                                <td>登录成功</td>
                            </tr>
                            <tr>
                                <td>2025-03-02 14:25:10</td>
                                <td><span class="badge bg-warning">文件</span></td>
                                <td>engineer01</td>
                                <td>上传文件</td>
                                <td>上传文件: 项目报告.docx</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    `;
    
    $('#system-content').html(content);
}

/**
 * 加载数据备份内容
 */
function loadDataBackup() {
    const content = `
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">数据备份</h5>
            </div>
            <div class="card-body">
                <div class="mb-4">
                    <h6>备份设置</h6>
                    <form>
                        <div class="mb-3">
                            <label class="form-label">自动备份</label>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="autoBackup" checked>
                                <label class="form-check-label" for="autoBackup">启用自动备份</label>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">备份频率</label>
                            <select class="form-select">
                                <option value="daily">每天</option>
                                <option value="weekly">每周</option>
                                <option value="monthly">每月</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">备份保留时间</label>
                            <div class="input-group">
                                <input type="number" class="form-control" value="30">
                                <span class="input-group-text">天</span>
                            </div>
                        </div>
                        <button type="submit" class="btn btn-primary">保存设置</button>
                        <button type="button" class="btn btn-success">
                            <i class="fas fa-download"></i> 立即备份
                        </button>
                    </form>
                </div>
                <div>
                    <h6>备份历史</h6>
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>备份时间</th>
                                    <th>文件大小</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>2025-03-02 00:00:00</td>
                                    <td>256 MB</td>
                                    <td><span class="badge bg-success">成功</span></td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary">下载</button>
                                        <button class="btn btn-sm btn-outline-success">恢复</button>
                                        <button class="btn btn-sm btn-outline-danger">删除</button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    $('#system-content').html(content);
}

/**
 * 加载智能业务配置页面
 */
function loadAiUsageConfig() {
    const content = `
        <div class="card mb-4">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">智能业务在线配置</h5>
                    <div>
                        <span class="badge bg-success connection-status">已连接</span>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <ul class="nav nav-tabs mb-4" id="aiConfigTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="basic-tab" data-bs-toggle="tab" data-bs-target="#basic" type="button" role="tab" aria-controls="basic" aria-selected="true">基础配置</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="advanced-tab" data-bs-toggle="tab" data-bs-target="#advanced" type="button" role="tab" aria-controls="advanced" aria-selected="false">高级设置</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="model-tab" data-bs-toggle="tab" data-bs-target="#model" type="button" role="tab" aria-controls="model" aria-selected="false">模型参数</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="usage-tab" data-bs-toggle="tab" data-bs-target="#usage" type="button" role="tab" aria-controls="usage" aria-selected="false">用量统计</button>
                    </li>
                </ul>
                
                <div class="tab-content" id="aiConfigTabContent">
                    <!-- 基础配置 -->
                    <div class="tab-pane fade show active" id="basic" role="tabpanel" aria-labelledby="basic-tab">
                        <form id="basicConfigForm">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">API密钥</label>
                                    <div class="input-group">
                                        <input type="password" class="form-control" id="apiKey" value="********">
                                        <button class="btn btn-outline-secondary toggle-password" type="button" data-target="apiKey">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                    </div>
                                    <div class="form-text">用于访问智能业务 API的密钥，请妥善保管</div>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">API版本</label>
                                    <select class="form-select" id="apiVersion">
                                        <option value="v1">v1 (稳定版)</option>
                                        <option value="v2">v2 (预览版)</option>
                                        <option value="beta">Beta (测试版)</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">API地址</label>
                                    <input type="url" class="form-control" id="apiUrl" value="https://api.intelligentbusiness.com/v1">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">默认模型</label>
                                    <select class="form-select" id="defaultModel">
                                        <option value="base">基础版</option>
                                        <option value="pro">专业版</option>
                                        <option value="expert">专家版</option>
                                        <option value="coder">编程版</option>
                                        <option value="chat">聊天版</option>
                                    </select>
                                </div>
                            </div>
                            <div class="d-flex justify-content-end gap-2 mt-4">
                                <button type="button" class="btn btn-primary" id="testConnection">测试连接</button>
                                <button type="button" class="btn btn-success" id="saveBasicConfig">保存配置</button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- 高级设置 -->
                    <div class="tab-pane fade" id="advanced" role="tabpanel" aria-labelledby="advanced-tab">
                        <form id="advancedConfigForm">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="form-label">并发请求数</label>
                                    <input type="number" class="form-control" id="concurrentRequests" value="5" min="1" max="20">
                                    <div class="form-text">同时处理的最大请求数量</div>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">请求超时</label>
                                    <div class="input-group">
                                        <input type="number" class="form-control" id="requestTimeout" value="30" min="5" max="120">
                                        <span class="input-group-text">秒</span>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">重试次数</label>
                                    <input type="number" class="form-control" id="retryCount" value="3" min="0" max="10">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">日志级别</label>
                                    <select class="form-select" id="logLevel">
                                        <option value="debug">Debug</option>
                                        <option value="info" selected>Info</option>
                                        <option value="warning">Warning</option>
                                        <option value="error">Error</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">缓存策略</label>
                                    <select class="form-select" id="cacheStrategy">
                                        <option value="memory">内存缓存</option>
                                        <option value="disk">磁盘缓存</option>
                                        <option value="hybrid" selected>混合缓存</option>
                                        <option value="none">禁用缓存</option>
                                    </select>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">代理设置</label>
                                    <div class="input-group">
                                        <span class="input-group-text">http://</span>
                                        <input type="text" class="form-control" id="proxyHost" placeholder="host">
                                        <span class="input-group-text">:</span>
                                        <input type="text" class="form-control" id="proxyPort" placeholder="port" style="max-width: 100px;">
                                    </div>
                                    <div class="form-text">如果您的网络需要代理才能访问智能业务 API，请填写代理地址</div>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="enableRateLimiting" checked>
                                        <label class="form-check-label" for="enableRateLimiting">启用请求频率限制</label>
                                    </div>
                                </div>
                            </div>
                            <div class="d-flex justify-content-end mt-4">
                                <button type="button" class="btn btn-success" id="saveAdvancedConfig">保存高级设置</button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- 模型参数 -->
                    <div class="tab-pane fade" id="model" role="tabpanel" aria-labelledby="model-tab">
                        <form id="modelConfigForm">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">模型温度 <span class="temperature-value">0.7</span></label>
                                    <input type="range" class="form-range" id="temperature" min="0" max="2" step="0.1" value="0.7">
                                    <div class="form-text">较低的值使输出更确定，较高的值使输出更随机</div>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">最大生成长度</label>
                                    <input type="number" class="form-control" id="maxTokens" value="2048" min="1" max="4096">
                                    <div class="form-text">每次请求生成的最大文本长度</div>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Top P <span class="top-p-value">0.95</span></label>
                                    <input type="range" class="form-range" id="topP" min="0" max="1" step="0.01" value="0.95">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Top K</label>
                                    <input type="number" class="form-control" id="topK" value="50" min="1" max="100">
                                </div>
                                <div class="col-12">
                                    <label class="form-label">系统提示词</label>
                                    <textarea class="form-control" id="systemPrompt" rows="3" placeholder="为AI助手设置基础行为和指令">您是由机勘院研发的智能业务系统助手，专注于道路勘察相关问题的解答。请根据用户提供的信息，给出准确、专业的回复。</textarea>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="enableStreaming" checked>
                                        <label class="form-check-label" for="enableStreaming">启用流式输出</label>
                                    </div>
                                    <div class="form-text">启用后，AI回复会实时显示</div>
                                </div>
                            </div>
                            <div class="d-flex justify-content-end mt-4">
                                <button type="button" class="btn btn-success" id="saveModelConfig">保存模型设置</button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- 用量统计 -->
                    <div class="tab-pane fade" id="usage" role="tabpanel" aria-labelledby="usage-tab">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        <h2 class="mb-2">156,248</h2>
                                        <p class="text-muted mb-0">本月总请求数</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        <h2 class="mb-2">2.56M</h2>
                                        <p class="text-muted mb-0">本月消耗Token</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        <h2 class="mb-2">¥1,284</h2>
                                        <p class="text-muted mb-0">本月费用</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h6 class="mb-0">每日用量趋势</h6>
                                    </div>
                                    <div class="card-body">
                                        <canvas id="usageChart" height="250"></canvas>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h6 class="mb-0">各模型使用占比</h6>
                                    </div>
                                    <div class="card-body">
                                        <canvas id="modelUsageChart" height="200"></canvas>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h6 class="mb-0">部门使用占比</h6>
                                    </div>
                                    <div class="card-body">
                                        <canvas id="departmentUsageChart" height="200"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">服务状态监控</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label">API连接状态</label>
                        <div class="progress">
                            <div class="progress-bar bg-success" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100">100%</div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">平均响应时间</label>
                        <div class="progress">
                            <div class="progress-bar bg-info" role="progressbar" style="width: 75%" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100">320ms</div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">当前并发连接数</label>
                        <div class="progress">
                            <div class="progress-bar bg-warning" role="progressbar" style="width: 40%" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100">4/10</div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">错误率</label>
                        <div class="progress">
                            <div class="progress-bar bg-danger" role="progressbar" style="width: 5%" aria-valuenow="5" aria-valuemin="0" aria-valuemax="100">0.05%</div>
                        </div>
                    </div>
                </div>
                
                <div class="mt-4">
                    <h6>最近错误日志</h6>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>时间</th>
                                    <th>错误类型</th>
                                    <th>描述</th>
                                    <th>请求ID</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>2025-03-10 14:23:15</td>
                                    <td><span class="badge bg-warning">超时</span></td>
                                    <td>请求超过30秒未响应</td>
                                    <td><code>req_2a9d8f3e</code></td>
                                </tr>
                                <tr>
                                    <td>2025-03-09 09:45:22</td>
                                    <td><span class="badge bg-danger">认证失败</span></td>
                                    <td>API密钥无效或已过期</td>
                                    <td><code>req_7b3e5f1c</code></td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    $('#system-content').html(content);
    
    // 初始化图表
    initAiUsageCharts();
    
    // 绑定事件
    bindAiConfigEvents();
}

/**
 * 初始化智能业务用量图表
 */
function initAiUsageCharts() {
    // 初始化用量趋势图表
    if(document.getElementById('usageChart')) {
        const usageCtx = document.getElementById('usageChart').getContext('2d');
        new Chart(usageCtx, {
            type: 'line',
            data: {
                labels: ['3/1', '3/2', '3/3', '3/4', '3/5', '3/6', '3/7', '3/8', '3/9', '3/10'],
                datasets: [{
                    label: 'API调用数',
                    data: [1200, 1900, 1500, 1700, 2100, 1800, 2300, 2500, 2200, 2400],
                    borderColor: '#2563eb',
                    backgroundColor: 'rgba(37, 99, 235, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }
    
    // 初始化模型使用占比图表
    if(document.getElementById('modelUsageChart')) {
        const modelCtx = document.getElementById('modelUsageChart').getContext('2d');
        new Chart(modelCtx, {
            type: 'doughnut',
            data: {
                labels: ['基础版', '专业版', '专家版', '编程版'],
                datasets: [{
                    data: [45, 30, 15, 10],
                    backgroundColor: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444']
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false
            }
        });
    }
    
    // 初始化部门使用占比图表
    if(document.getElementById('departmentUsageChart')) {
        const deptCtx = document.getElementById('departmentUsageChart').getContext('2d');
        new Chart(deptCtx, {
            type: 'doughnut',
            data: {
                labels: ['系统管理部', '项目管理部', '道路勘察部', '数据分析部'],
                datasets: [{
                    data: [15, 20, 45, 20],
                    backgroundColor: ['#6366f1', '#ec4899', '#14b8a6', '#f97316']
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false
            }
        });
    }
}

/**
 * 绑定智能业务配置页面事件
 */
function bindAiConfigEvents() {
    // 从API连接器加载配置
    loadAiConfigFromAPI();
    
    // 密码显示/隐藏切换
    $('.toggle-password').on('click', function() {
        const targetId = $(this).data('target');
        const input = $('#' + targetId);
        const icon = $(this).find('i');
        
        if (input.attr('type') === 'password') {
            input.attr('type', 'text');
            icon.removeClass('fa-eye').addClass('fa-eye-slash');
        } else {
            input.attr('type', 'password');
            icon.removeClass('fa-eye-slash').addClass('fa-eye');
        }
    });
    
    // 温度滑块值更新
    $('#temperature').on('input', function() {
        $('.temperature-value').text($(this).val());
    });
    
    // Top P滑块值更新
    $('#topP').on('input', function() {
        $('.top-p-value').text($(this).val());
    });
    
    // 测试连接
    $('#testConnection').on('click', function() {
        const button = $(this);
        button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 测试中...');
        
        // 先保存当前配置
        const config = {
            apiKey: $('#apiKey').val(),
            apiUrl: $('#apiUrl').val(),
            apiVersion: $('#apiVersion').val(),
            defaultModel: $('#defaultModel').val()
        };
        
        // 保存配置
        aiAPI.saveConfig(config);
        
        // 测试连接
        aiAPI.testConnection()
            .then(result => {
                showToast('success', '智能业务 API连接成功！');
                // 刷新服务状态显示
                updateServiceStatus();
            })
            .catch(error => {
                showToast('danger', `智能业务 API连接失败: ${error.message}`);
            })
            .finally(() => {
                button.prop('disabled', false).text('测试连接');
            });
    });
    
    // 保存基础配置
    $('#saveBasicConfig').on('click', function() {
        const button = $(this);
        button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...');
        
        // 收集表单数据
        const config = {
            apiKey: $('#apiKey').val(),
            apiVersion: $('#apiVersion').val(),
            apiUrl: $('#apiUrl').val(),
            defaultModel: $('#defaultModel').val()
        };
        
        // 保存到API连接器
        if (aiAPI.saveConfig(config)) {
            showToast('success', '基础配置保存成功');
        } else {
            showToast('danger', '保存配置失败，请检查输入');
        }
        
        button.prop('disabled', false).text('保存配置');
    });
    
    // 保存高级设置
    $('#saveAdvancedConfig').on('click', function() {
        // 收集表单数据
        const config = {
            concurrentRequests: $('#concurrentRequests').val(),
            requestTimeout: $('#requestTimeout').val(),
            retryCount: $('#retryCount').val(),
            logLevel: $('#logLevel').val(),
            cacheStrategy: $('#cacheStrategy').val(),
            proxy: $('#proxyHost').val() ? `http://${$('#proxyHost').val()}:${$('#proxyPort').val()}` : null,
            enableRateLimiting: $('#enableRateLimiting').is(':checked')
        };
        
        // 保存到API连接器
        if (aiAPI.saveConfig(config)) {
            showToast('success', '高级设置保存成功');
        } else {
            showToast('danger', '保存高级设置失败，请检查输入');
        }
    });
    
    // 保存模型设置
    $('#saveModelConfig').on('click', function() {
        // 收集表单数据
        const config = {
            temperature: $('#temperature').val(),
            maxTokens: $('#maxTokens').val(),
            topP: $('#topP').val(),
            topK: $('#topK').val(),
            systemPrompt: $('#systemPrompt').val(),
            enableStreaming: $('#enableStreaming').is(':checked')
        };
        
        // 保存到localStorage，这些模型设置不直接保存到API连接器
        localStorage.setItem('ai_model_config', JSON.stringify(config));
        showToast('success', '模型设置保存成功');
    });
    
    // 加载用量图表和服务状态
    updateUsageStats();
    updateServiceStatus();
}

/**
 * 从API连接器加载配置到表单
 */
function loadAiConfigFromAPI() {
    // 加载基础配置
    if (aiAPI.baseUrl) $('#apiUrl').val(aiAPI.baseUrl);
    if (aiAPI.apiKey) $('#apiKey').val(aiAPI.apiKey);
    if (aiAPI.apiVersion) $('#apiVersion').val(aiAPI.apiVersion);
    if (aiAPI.defaultModel) $('#defaultModel').val(aiAPI.defaultModel);
    
    // 加载高级设置
    $('#concurrentRequests').val(aiAPI.concurrentRequests);
    $('#requestTimeout').val(aiAPI.timeout / 1000);
    $('#retryCount').val(aiAPI.retryCount);
    $('#enableRateLimiting').prop('checked', aiAPI.rateLimiter);
    
    // 加载模型设置（从localStorage）
    try {
        const modelConfig = JSON.parse(localStorage.getItem('ai_model_config'));
        if (modelConfig) {
            if (modelConfig.temperature) {
                $('#temperature').val(modelConfig.temperature);
                $('.temperature-value').text(modelConfig.temperature);
            }
            if (modelConfig.maxTokens) $('#maxTokens').val(modelConfig.maxTokens);
            if (modelConfig.topP) {
                $('#topP').val(modelConfig.topP);
                $('.top-p-value').text(modelConfig.topP);
            }
            if (modelConfig.topK) $('#topK').val(modelConfig.topK);
            if (modelConfig.systemPrompt) $('#systemPrompt').val(modelConfig.systemPrompt);
            if (modelConfig.enableStreaming !== undefined) $('#enableStreaming').prop('checked', modelConfig.enableStreaming);
        }
    } catch (error) {
        console.error('加载模型配置失败:', error);
    }
    
    // 连接状态初始化
    updateConnectionStatus();
}

/**
 * 更新连接状态显示
 */
function updateConnectionStatus() {
    const isConnected = aiAPI.baseUrl && aiAPI.apiKey;
    const statusElement = $('.connection-status');
    
    if (statusElement.length) {
        if (isConnected) {
            statusElement.removeClass('bg-danger bg-warning').addClass('bg-success').text('已连接');
        } else {
            statusElement.removeClass('bg-success bg-warning').addClass('bg-danger').text('未配置');
        }
    }
}

/**
 * 更新用量统计
 */
function updateUsageStats() {
    // 从API连接器获取用量统计数据
    const usageStats = aiAPI.getUsageStats();
    
    // 更新统计卡片
    if (usageStats.monthly) {
        const { requests, tokens, cost } = usageStats.monthly;
        $('.col-md-4:nth-child(1) h2').text(requests.toLocaleString());
        $('.col-md-4:nth-child(2) h2').text(`${(tokens / 1000000).toFixed(2)}M`);
        $('.col-md-4:nth-child(3) h2').text(`¥${cost.toLocaleString()}`);
    }
    
    // 更新趋势图表
    if (usageStats.daily && document.getElementById('usageChart')) {
        const usageCtx = document.getElementById('usageChart').getContext('2d');
        const chart = new Chart(usageCtx, {
            type: 'line',
            data: {
                labels: usageStats.daily.map(item => item.date),
                datasets: [{
                    label: 'API调用数',
                    data: usageStats.daily.map(item => item.requests),
                    borderColor: '#2563eb',
                    backgroundColor: 'rgba(37, 99, 235, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }
    
    // 更新模型使用占比图表
    if (usageStats.models && document.getElementById('modelUsageChart')) {
        const modelCtx = document.getElementById('modelUsageChart').getContext('2d');
        const chart = new Chart(modelCtx, {
            type: 'doughnut',
            data: {
                labels: usageStats.models.map(item => item.name),
                datasets: [{
                    data: usageStats.models.map(item => item.usage),
                    backgroundColor: ['#3b82f6', '#10b981', '#f59e0b', '#ef4444']
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false
            }
        });
    }
    
    // 更新部门使用占比图表
    if (usageStats.departments && document.getElementById('departmentUsageChart')) {
        const deptCtx = document.getElementById('departmentUsageChart').getContext('2d');
        const chart = new Chart(deptCtx, {
            type: 'doughnut',
            data: {
                labels: usageStats.departments.map(item => item.name),
                datasets: [{
                    data: usageStats.departments.map(item => item.usage),
                    backgroundColor: ['#6366f1', '#ec4899', '#14b8a6', '#f97316']
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false
            }
        });
    }
}

/**
 * 更新服务状态
 */
function updateServiceStatus() {
    // 从API连接器获取服务状态数据
    const status = aiAPI.getServiceStatus();
    
    // 更新进度条
    if (status) {
        // API连接状态
        $('.progress-bar:nth-child(1)').css('width', `${status.apiConnection}%`).text(`${status.apiConnection}%`);
        
        // 平均响应时间
        const responseTimePercent = Math.min(100, (status.responseTime / 10));
        $('.progress-bar:nth-child(2)').css('width', `${responseTimePercent}%`).text(`${status.responseTime}ms`);
        
        // 当前并发连接数
        const { current, max } = status.concurrentConnections;
        const connectionPercent = (current / max) * 100;
        $('.progress-bar:nth-child(3)').css('width', `${connectionPercent}%`).text(`${current}/${max}`);
        
        // 错误率
        const errorPercent = Math.min(100, status.errorRate * 100);
        $('.progress-bar:nth-child(4)').css('width', `${errorPercent}%`).text(`${errorPercent.toFixed(2)}%`);
        
        // 更新错误日志表格
        if (status.recentErrors && status.recentErrors.length) {
            let errorRows = '';
            status.recentErrors.forEach(error => {
                let badgeClass = 'bg-warning';
                if (error.type === 'auth_error') badgeClass = 'bg-danger';
                
                errorRows += `
                    <tr>
                        <td>${error.timestamp}</td>
                        <td><span class="badge ${badgeClass}">${error.type === 'auth_error' ? '认证失败' : '超时'}</span></td>
                        <td>${error.description}</td>
                        <td><code>${error.requestId}</code></td>
                    </tr>
                `;
            });
            
            $('.table-sm tbody').html(errorRows);
        }
    }
}

/**
 * 保存用户
 */
function saveUser() {
    // 获取表单数据
    const userData = {
        username: $('#username').val().trim(),
        fullName: $('#fullName').val().trim(),
        password: $('#password').val(),
        confirmPassword: $('#confirmPassword').val(),
        email: $('#userEmail').val().trim(),
        phone: $('#userPhone').val().trim(),
        role: $('#userRole').val(),
        department: $('#userDepartment').val(),
        permissions: getSelectedPermissions(),
        active: $('#userActive').is(':checked'),
        remarks: $('#userRemarks').val().trim()
    };
    
    // 验证表单
    if (!validateUserForm(userData)) {
        return;
    }
    
    // 显示保存中状态
    const $saveBtn = $('#saveUserBtn');
    $saveBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 保存中...');
    
    // 在实际应用中，这里应该调用API保存用户数据
    setTimeout(function() {
        // 保存完成
        $saveBtn.prop('disabled', false).text('保存');
        $('#addUserModal').modal('hide');
        
        // 清空表单
        $('#addUserForm')[0].reset();
        
        // 显示成功消息
        showToast('success', '用户保存成功！');
        
        // 刷新用户列表
        refreshUserList();
    }, 1000);
}

/**
 * 获取选中的权限
 * @returns {string[]} 权限列表
 */
function getSelectedPermissions() {
    const permissions = [];
    $('input[type="checkbox"][id^="perm"]:checked').each(function() {
        permissions.push($(this).next('label').text().trim());
    });
    return permissions;
}

/**
 * 验证用户表单
 * @param {Object} userData - 用户数据
 * @returns {boolean} 验证结果
 */
function validateUserForm(userData) {
    if (!userData.username) {
        showToast('error', '请输入用户名');
        return false;
    }
    
    if (!userData.fullName) {
        showToast('error', '请输入姓名');
        return false;
    }
    
    if (!$('#addUserModal').data('editMode')) {
        if (!userData.password) {
            showToast('error', '请输入密码');
            return false;
        }
        
        if (userData.password !== userData.confirmPassword) {
            showToast('error', '两次输入的密码不一致');
            return false;
        }
        
        if (userData.password.length < 8) {
            showToast('error', '密码长度不能少于8位');
            return false;
        }
    }
    
    if (!userData.role) {
        showToast('error', '请选择用户角色');
        return false;
    }
    
    if (!userData.department) {
        showToast('error', '请选择所属部门');
        return false;
    }
    
    if (userData.email && !validateEmail(userData.email)) {
        showToast('error', '请输入有效的电子邮箱地址');
        return false;
    }
    
    if (userData.phone && !validatePhone(userData.phone)) {
        showToast('error', '请输入有效的手机号码');
        return false;
    }
    
    return true;
}

/**
 * 验证电子邮箱
 * @param {string} email - 电子邮箱地址
 * @returns {boolean} 验证结果
 */
function validateEmail(email) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

/**
 * 验证手机号码
 * @param {string} phone - 手机号码
 * @returns {boolean} 验证结果
 */
function validatePhone(phone) {
    return /^1[3-9]\d{9}$/.test(phone);
}

/**
 * 编辑用户
 * @param {jQuery} row - 用户表格行
 */
function editUser(row) {
    const username = row.find('.fw-bold').text();
    const email = row.find('.text-muted').text();
    const role = row.find('td:eq(1)').text();
    const department = row.find('td:eq(2)').text();
    
    // 填充表单
    $('#username').val(username);
    $('#userEmail').val(email);
    $('#userRole').val(role);
    $('#userDepartment').val(department);
    
    // 密码字段处理
    $('#password, #confirmPassword')
        .val('')
        .prop('required', false)
        .closest('.row').hide();
    
    // 标记为编辑模式
    $('#addUserModal')
        .data('editMode', true)
        .find('.modal-title').text('编辑用户');
    
    // 显示模态框
    $('#addUserModal').modal('show');
}

/**
 * 刷新用户列表
 */
function refreshUserList() {
    // 在实际应用中，这里应该通过API获取最新的用户列表
    // 这里仅做演示，重新加载当前页面
    loadUserManagement();
}

/**
 * 显示提示消息
 * @param {string} type - 消息类型（success/error/warning/info）
 * @param {string} message - 消息内容
 */
function showToast(type, message) {
    const bgClass = {
        success: 'bg-success',
        error: 'bg-danger',
        warning: 'bg-warning',
        info: 'bg-info'
    }[type];
    
    const toast = $([
        '<div class="toast align-items-center text-white ' + bgClass + ' border-0" role="alert" aria-live="assertive" aria-atomic="true">',
        '    <div class="d-flex">',
        '        <div class="toast-body">' + message + '</div>',
        '        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>',
        '    </div>',
        '</div>'
    ].join('\n'));
    
    // 添加到容器
    if (!$('#toastContainer').length) {
        $('body').append('<div id="toastContainer" class="toast-container position-fixed top-0 end-0 p-3"></div>');
    }
    
    $('#toastContainer').append(toast);
    
    // 显示提示
    const bsToast = new bootstrap.Toast(toast[0], {
        animation: true,
        autohide: true,
        delay: 3000
    });
    
    bsToast.show();
    
    // 移除已关闭的提示
    toast.on('hidden.bs.toast', function() {
        $(this).remove();
    });
}

/**
 * 切换用户状态
 * @param {jQuery} row - 用户表格行
 */
function toggleUserStatus(row) {
    const username = row.find('td:first').text();
    const status = row.find('.badge');
    const isActive = status.hasClass('bg-success');
    
    if (confirm(`确定要${isActive ? '禁用' : '启用'}用户 "${username}" 吗？`)) {
        // 在实际应用中，这里应该调用API修改用户状态
        
        // 更新状态显示
        if (isActive) {
            status.removeClass('bg-success').addClass('bg-secondary').text('未登录');
        } else {
            status.removeClass('bg-secondary').addClass('bg-success').text('活跃');
        }
        
        showToast('success', `用户 ${username} 已${isActive ? '禁用' : '启用'}`);
    }
}

// 资源监控图表实现
function loadResourceMonitoring() {
    const content = `
        <div class="row">
            <div class="col-xl-12">
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">系统资源监控</h5>
                        <div class="btn-group" role="group">
                            <button type="button" class="btn btn-outline-primary active" data-type="cpu">CPU</button>
                            <button type="button" class="btn btn-outline-primary" data-type="memory">内存</button>
                            <button type="button" class="btn btn-outline-primary" data-type="disk">磁盘</button>
                            <button type="button" class="btn btn-outline-primary" data-type="network">网络</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row mb-4">
                            <div class="col-md-3">
                                <div class="stat-card">
                                    <div class="stat-card-body">
                                        <div class="stat-card-icon bg-primary">
                                            <i class="fas fa-microchip"></i>
                                        </div>
                                        <div>
                                            <h6 class="stat-card-title">CPU使用率</h6>
                                            <h3 class="stat-card-value">42%</h3>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-card">
                                    <div class="stat-card-body">
                                        <div class="stat-card-icon bg-success">
                                            <i class="fas fa-memory"></i>
                                        </div>
                                        <div>
                                            <h6 class="stat-card-title">内存使用</h6>
                                            <h3 class="stat-card-value">6.2 GB</h3>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-card">
                                    <div class="stat-card-body">
                                        <div class="stat-card-icon bg-info">
                                            <i class="fas fa-hdd"></i>
                                        </div>
                                        <div>
                                            <h6 class="stat-card-title">存储空间</h6>
                                            <h3 class="stat-card-value">256 GB</h3>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-card">
                                    <div class="stat-card-body">
                                        <div class="stat-card-icon bg-warning">
                                            <i class="fas fa-network-wired"></i>
                                        </div>
                                        <div>
                                            <h6 class="stat-card-title">网络吞吐量</h6>
                                            <h3 class="stat-card-value">5.8 MB/s</h3>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div>
                            <canvas id="resourceChart" height="300"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    $('#system-content').html(content);
    
    // 初始化资源监控图表
    initResourceChart('cpu');
}

// 初始化资源图表
function initResourceChart(type) {
    const ctx = document.getElementById('resourceChart').getContext('2d');
    
    // 销毁已有的图表实例
    if (resourceChart) {
        resourceChart.destroy();
    }
    
    // 配置图表数据
    const timeLabels = Array.from({length: 24}, (_, i) => `${i}:00`);
    const data = generateRandomData(timeLabels.length, type);
    
    // 创建新的图表实例
    resourceChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: timeLabels,
            datasets: [{
                label: getResourceLabel(type),
                data: data,
                borderColor: getResourceColor(type),
                backgroundColor: getResourceBackgroundColor(type),
                tension: 0.3,
                fill: 'origin'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                intersect: false,
                mode: 'index'
            },
            scales: {
                y: {
                    suggestedMin: 0,
                    suggestedMax: type === 'network' ? 10 : 100,
                    title: {
                        display: true,
                        text: getResourceUnit(type)
                    }
                }
            },
            plugins: {
                legend: {
                    display: true,
                    position: 'top'
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            let label = context.dataset.label || '';
                            if (label) {
                                label += ': ';
                            }
                            if (context.parsed.y !== null) {
                                label += context.parsed.y + getResourceUnit(type);
                            }
                            return label;
                        }
                    }
                }
            }
        }
    });
}

// 更新资源图表数据
function updateResourceChart(type) {
    if (!resourceChart) return;
    
    const data = generateRandomData(resourceChart.data.labels.length, type);
    
    resourceChart.data.datasets[0].label = getResourceLabel(type);
    resourceChart.data.datasets[0].data = data;
    resourceChart.data.datasets[0].borderColor = getResourceColor(type);
    resourceChart.data.datasets[0].backgroundColor = getResourceBackgroundColor(type);
    
    resourceChart.options.scales.y.suggestedMax = type === 'network' ? 10 : 100;
    resourceChart.options.scales.y.title.text = getResourceUnit(type);
    
    resourceChart.update();
}

// 获取资源类型标签
function getResourceLabel(type) {
    const labels = {
        'cpu': 'CPU使用率',
        'memory': '内存使用率',
        'disk': '磁盘使用率',
        'network': '网络吞吐量'
    };
    return labels[type] || '';
}

// 获取资源类型单位
function getResourceUnit(type) {
    const units = {
        'cpu': '%',
        'memory': '%',
        'disk': '%',
        'network': 'MB/s'
    };
    return units[type] || '';
}

// 获取资源类型颜色
function getResourceColor(type) {
    const colors = {
        'cpu': '#4361ee',
        'memory': '#3a0ca3',
        'disk': '#7209b7',
        'network': '#f59e0b'
    };
    return colors[type] || '#4361ee';
}

// 获取资源类型背景色
function getResourceBackgroundColor(type) {
    const colors = {
        'cpu': 'rgba(67, 97, 238, 0.1)',
        'memory': 'rgba(58, 12, 163, 0.1)',
        'disk': 'rgba(114, 9, 183, 0.1)',
        'network': 'rgba(247, 37, 133, 0.1)'
    };
    return colors[type] || 'rgba(67, 97, 238, 0.1)';
}

// 生成随机数据
function generateRandomData(length, type) {
    let min, max;
    
    switch(type) {
        case 'network':
            min = 0.5;
            max = 8;
            break;
        default:
            min = 10;
            max = 80;
    }
    
    return Array.from({length}, () => Math.floor(Math.random() * (max - min + 1)) + min);
}

// AI配置管理
function loadAiConfig() {
    const content = `
        <div class="row">
            <div class="col-xl-12">
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">AI模型配置</h5>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#aiModelModal">
                            <i class="fas fa-plus me-1"></i>添加模型
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table system-table">
                                <thead>
                                    <tr>
                                        <th>模型名称</th>
                                        <th>类型</th>
                                        <th>API密钥</th>
                                        <th>状态</th>
                                        <th>最大Tokens</th>
                                        <th>温度</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>DeepSeek-Coder</td>
                                        <td>代码生成</td>
                                        <td>······························</td>
                                        <td><span class="badge bg-success">已启用</span></td>
                                        <td>8192</td>
                                        <td>0.7</td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <button class="btn btn-outline-secondary" data-bs-toggle="tooltip" title="编辑配置">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-outline-secondary" data-bs-toggle="tooltip" title="测试连接">
                                                    <i class="fas fa-vial"></i>
                                                </button>
                                                <button class="btn btn-outline-danger" data-bs-toggle="tooltip" title="禁用模型">
                                                    <i class="fas fa-ban"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>DeepSeek-Vision</td>
                                        <td>图像分析</td>
                                        <td>······························</td>
                                        <td><span class="badge bg-success">已启用</span></td>
                                        <td>4096</td>
                                        <td>0.5</td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <button class="btn btn-outline-secondary" data-bs-toggle="tooltip" title="编辑配置">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-outline-secondary" data-bs-toggle="tooltip" title="测试连接">
                                                    <i class="fas fa-vial"></i>
                                                </button>
                                                <button class="btn btn-outline-danger" data-bs-toggle="tooltip" title="禁用模型">
                                                    <i class="fas fa-ban"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>OpenAI-GPT-4</td>
                                        <td>文本分析</td>
                                        <td>······························</td>
                                        <td><span class="badge bg-secondary">已禁用</span></td>
                                        <td>16384</td>
                                        <td>0.8</td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <button class="btn btn-outline-secondary" data-bs-toggle="tooltip" title="编辑配置">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-outline-secondary" data-bs-toggle="tooltip" title="测试连接">
                                                    <i class="fas fa-vial"></i>
                                                </button>
                                                <button class="btn btn-outline-success" data-bs-toggle="tooltip" title="启用模型">
                                                    <i class="fas fa-check"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    $('#system-content').html(content);
    initTooltips();
}

// AI配置相关事件
function bindAiConfigEvents() {
    // 模拟绑定AI配置弹窗事件
    $(document).on('click', '[data-bs-target="#aiModelModal"]', function() {
        // 实际项目中这里应打开模态窗口
        alert('打开添加AI模型配置窗口');
    });
}

// 绑定用户管理相关事件
function bindUserManagementEvents() {
    // 搜索用户事件
    $(document).on('input', '.card-body .input-group input', function() {
        const query = $(this).val().toLowerCase();
        searchUsers(query);
    });
    
    // 角色筛选事件
    $(document).on('change', '.card-body select:eq(0)', function() {
        const role = $(this).val();
        filterUsersByRole(role);
    });
    
    // 部门筛选事件
    $(document).on('change', '.card-body select:eq(1)', function() {
        const department = $(this).val();
        filterUsersByDepartment(department);
    });
}

// 搜索用户
function searchUsers(query) {
    if (!query) {
        $('.system-table tbody tr').show();
        return;
    }
    
    $('.system-table tbody tr').each(function() {
        const $row = $(this);
        const username = $row.find('td:first-child .fw-bold').text().toLowerCase();
        const email = $row.find('td:first-child .small').text().toLowerCase();
        
        if (username.includes(query) || email.includes(query)) {
            $row.show();
        } else {
            $row.hide();
        }
    });
}

// 按角色筛选用户
function filterUsersByRole(role) {
    if (role === 'all') {
        $('.system-table tbody tr').show();
        return;
    }
    
    $('.system-table tbody tr').each(function() {
        const $row = $(this);
        const userRole = $row.find('td:nth-child(2)').text().toLowerCase();
        
        if (role === 'admin' && userRole === '管理员' ||
            role === 'manager' && userRole === '项目经理' ||
            role === 'engineer' && userRole === '工程师') {
            $row.show();
        } else {
            $row.hide();
        }
    });
}

// 按部门筛选用户
function filterUsersByDepartment(department) {
    if (department === 'all') {
        $('.system-table tbody tr').show();
        return;
    }
    
    $('.system-table tbody tr').each(function() {
        const $row = $(this);
        const userDepartment = $row.find('td:nth-child(3)').text();
        
        if (department === 'system' && userDepartment === '系统管理部' ||
            department === 'project' && userDepartment === '项目管理部' ||
            department === 'road' && userDepartment === '道路勘察部') {
            $row.show();
        } else {
            $row.hide();
        }
    });
}

// 公开给主页面调用的功能
window.loadTabContent = function(tabId) {
    // 清空内容区域
    $('#system-content').empty();
    
    console.log('加载标签内容:', tabId);
    
    // 根据tabId加载对应内容
    switch(tabId) {
        case 'dashboard':
            loadResourceMonitoring();
            break;
        case 'users':
            loadUserManagement();
            break;
        case 'roles':
            loadPermissionSettings();
            break;
        case 'logs':
            loadSystemLogs();
            break;
        case 'backup':
            loadDataBackup();
            break;
        case 'ai-config':
            loadAiConfig();
            break;
        default:
            loadResourceMonitoring(); // 默认加载资源监控
    }
};
window.initSystemResourceChart = initSystemResourceChart;
window.loadUserManagement = loadUserManagement;
window.loadPermissionSettings = loadPermissionSettings;
window.loadSystemLogs = loadSystemLogs;
window.loadDataBackup = loadDataBackup;
window.loadAiConfig = loadAiConfig;
window.loadResourceMonitoring = loadResourceMonitoring;